#!/bin/sh

OUTPUT="$1"; shift

ME=`dirname $0`
ME=`cd $ME; pwd`

if [ -z "$1" ] || [ -z "$OUTPUT" ]; then
	echo "usage: $0 <output dmg> <input pkg> [<input pkg 2> <input pkg 3> ...]"
	exit 1
fi

LOGFILE=`mktemp /tmp/log.XXXXXX`
TEMPDIR=`mktemp -d /tmp/pkg-to-dmg.XXXXXX`
TEMPDMG=`mktemp /tmp/XXXXXX`
rm -rf "$TEMPDMG"
TEMPDMG="$TEMPDMG.dmg"

OUTPUTDIR=`dirname $OUTPUT`; OUTPUTDIR=`cd $OUTPUTDIR; pwd`
OUTPUTFILE=`basename $OUTPUT`

echo "* building $OUTPUTFILE"

die() {
	echo "failed: $@"
	if [ -s "$LOGFILE" ]; then
		cat $LOGFILE
	fi
	rm -rf "$TEMPDIR" "$LOGFILE"
	exit 1
}


for INPUT in "$@"; do
	PACKAGENAME=`basename $INPUT | sed -e 's,.(pkg|mpkg)$,,'`
	INPUTDIR=`dirname $INPUT`; INPUTDIR=`cd $INPUTDIR; pwd`
	INPUTFILE=`basename $INPUT`

	echo "- copying $INPUTFILE to temporary directory"
	/usr/bin/ditto "$INPUTDIR/$INPUTFILE" "$TEMPDIR/$INPUTFILE" >$LOGFILE 2>&1 || die "unable to copy $INPUTFILE to temporary directory"
done

echo "- creating disk image"
/usr/bin/hdiutil create -volname "$PACKAGENAME" -srcfolder "$TEMPDIR" -format UDBZ -ov "$OUTPUTDIR/$OUTPUTFILE" >$LOGFILE 2>&1 || die "hdiutil exited with an error"

echo "- internet enabling disk image"
/usr/bin/hdiutil internet-enable -yes "$OUTPUTDIR/$OUTPUTFILE" >$LOGFILE 2>&1

echo "- cleaning up"
rm -rf "$TEMPDIR" "$LOGFILE" "$TEMPDMG"
